﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.Data.Core.DatabaseObjects;
using ICSharpCode.Data.Oracle.ControlPanel;
using System.Windows.Controls;
using ICSharpCode.Data.Core.Interfaces;
using System.Windows;
using System.Windows.Threading;
using System.Data.SqlClient;

namespace ICSharpCode.Data.Core.DatabaseDrivers.Oracle
{
    public class OracleDatasource : Datasource
    {
        #region Fields

        private OracleControlPanel _controlPanel = null;

        #endregion

        #region Properties

        public override UserControl ControlPanel
        {
            get {  return _controlPanel; }
        }

        public string UserId
        {
            get { return GetConnectionStringSetting("UID"); }
            set 
            { 
                SetConnectionStringSetting("UID", value);
                OnPropertyChanged("UserId");
            }
        }

        public string Password
        {
            get { return GetConnectionStringSetting("PWD"); }
            set 
            { 
                SetConnectionStringSetting("PWD", value);
                OnPropertyChanged("Password");
            }
        }

        /*public string InitialCatalog
        {
            get { return GetConnectionStringSetting("InitialCatalog"); }
            set
            {
                SetConnectionStringSetting("InitialCatalog", value);
                OnPropertyChanged("InitialCatalog");
            }
        }*/

        #endregion

        #region Constructor

        public OracleDatasource(IDatabaseDriver databaseDriver)
            : base(databaseDriver)
        {            
            Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() =>
            {
                _controlPanel = new OracleControlPanel(this);
            }));
        }

        #endregion

        #region Methods

        protected override bool HandlePopulateDatabasesException(Exception exception)
        {
        	if (exception is SqlException) {
        		SqlException sqlException = exception as SqlException;
        		
        		if (sqlException.Number == 67) {
        			DatabaseDriver.RemoveDatasource(Name);
        			MessageBox.Show("Error while trying to populate databases.\n\n" + exception.Message, DatabaseDriver.Name, MessageBoxButton.OK, MessageBoxImage.Exclamation);
        			return false;
        		} else {
        			throw exception;
        		}
        	} else if (exception is NotSupportedException) {
        		DatabaseDriver.RemoveDatasource(Name);
        		MessageBox.Show("Error while trying to populate databases.\n\n" + exception.Message, DatabaseDriver.Name, MessageBoxButton.OK, MessageBoxImage.Exclamation);
        		return false;
        	} else {
        		throw exception;
        	}
        }

        #endregion
    }
}
